package com.lsh.security.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/8/18 12:02 下午
 * @desc ：
 */
@RestController
public class LoginController {
    @RequestMapping(value = "/login-success",produces = "text/plain;charset=UTF-8")
    public String loginSuccess(){
        return getUserName()+" 登录成功！";
    }

    /**
     * //开启SpringSecurity注解后，原本在配置类中配置的路径和角色对应关系由注解取代
     * @PreAuthorize可以用来控制一个方法是否能够被调用。请求方法之前检验
     * @PostAuthorize()方法之后执行
     * 其中的hasRole是固定写法,是Spring规定的表达式 SpEL
     */
    @PreAuthorize("permitAll()")
    @GetMapping("/anno")
    public String anonymous(){
        return getUserName()+"，匿名访问";

    }

    @PreAuthorize("hasPermission('/r/r1','p1')")
    @GetMapping("/r/r1")
    public String r1(){
        return getUserName()+"，具有p1的权限，访问r1";

    }
    @PreAuthorize("hasPermission('/r/r2','p2')")
    @GetMapping("/r/r2")
    public String r2(){
        return getUserName()+"，具有p2的权限，访问r2";

    }
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/r/r3")
    public String r3(){
        return getUserName()+" ，具有ADMIN的角色，访问r3";

    }
    @PreAuthorize("hasRole('ROLE_USER')")
    @GetMapping("/r/r4")
    public String r4(){
        return getUserName()+"，具有USER的角色，访问r4";

    }

    public String getUserName(){
        String username = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal == null){
            username = "匿名";
        }else {
            if (principal instanceof UserDetails){
                UserDetails userDetails = (UserDetails) principal;
                username = userDetails.getUsername();
            }else{
                username = principal.toString();
            }

        }

        return username;
    }


}
